#include "motor_postion.h"
#include "delay.h"




void postion_init(void)
{
	GPIO_InitTypeDef GPIO;
	TIM_TimeBaseInitTypeDef TIMER1;
	TIM_ICInitTypeDef IC_ENCODER;
	NVIC_InitTypeDef NVIC_TIM1;
	
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);
	
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource6,GPIO_AF_TIM3);
  GPIO_PinAFConfig(GPIOA,GPIO_PinSource7,GPIO_AF_TIM3);
	GPIO_PinAFConfig(GPIOB,GPIO_PinSource6,GPIO_AF_TIM4);
  GPIO_PinAFConfig(GPIOB,GPIO_PinSource7,GPIO_AF_TIM4);
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource0,GPIO_AF_TIM5);
  GPIO_PinAFConfig(GPIOA,GPIO_PinSource1,GPIO_AF_TIM5);
	
	GPIO.GPIO_Mode=GPIO_Mode_AF;
	GPIO.GPIO_Pin=GPIO_Pin_6|GPIO_Pin_7|GPIO_Pin_0|GPIO_Pin_1;
	GPIO.GPIO_Speed=GPIO_Speed_100MHz;
	GPIO.GPIO_PuPd=GPIO_PuPd_DOWN;
	GPIO_Init(GPIOA,&GPIO);
	GPIO_Init(GPIOB,&GPIO);
	
	TIMER1.TIM_Prescaler=0;
	TIMER1.TIM_Period=0xffff;
	TIMER1.TIM_ClockDivision=TIM_CKD_DIV1;
	TIMER1.TIM_CounterMode=TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM3,&TIMER1);
	TIM_TimeBaseInit(TIM4,&TIMER1);
	TIM_TimeBaseInit(TIM5,&TIMER1);
	
	TIM_EncoderInterfaceConfig(TIM3,TIM_EncoderMode_TI12,TIM_ICPolarity_Falling,TIM_ICPolarity_Falling);
	TIM_EncoderInterfaceConfig(TIM4,TIM_EncoderMode_TI12,TIM_ICPolarity_Falling,TIM_ICPolarity_Falling);
	TIM_EncoderInterfaceConfig(TIM5,TIM_EncoderMode_TI12,TIM_ICPolarity_Falling,TIM_ICPolarity_Falling);
	
	IC_ENCODER.TIM_Channel=TIM_Channel_1;
	IC_ENCODER.TIM_ICSelection=TIM_ICSelection_DirectTI;
  IC_ENCODER.TIM_ICFilter=0xf;
	TIM_ICInit(TIM3,&IC_ENCODER);
	TIM_ICInit(TIM4,&IC_ENCODER);
	TIM_ICInit(TIM5,&IC_ENCODER);
	IC_ENCODER.TIM_Channel        =        TIM_Channel_2;
  IC_ENCODER.TIM_ICSelection        =        TIM_ICSelection_DirectTI;
  TIM_ICInit(TIM3, &IC_ENCODER);
	TIM_ICInit(TIM4, &IC_ENCODER);
	TIM_ICInit(TIM5, &IC_ENCODER);
	
	NVIC_TIM1.NVIC_IRQChannel=TIM3_IRQn;
	NVIC_TIM1.NVIC_IRQChannelPreemptionPriority=0;
	NVIC_TIM1.NVIC_IRQChannelSubPriority=3;
	NVIC_TIM1.NVIC_IRQChannelCmd=ENABLE;
	NVIC_Init(&NVIC_TIM1);
	
	NVIC_TIM1.NVIC_IRQChannel=TIM4_IRQn;
	NVIC_TIM1.NVIC_IRQChannelPreemptionPriority=2;
	NVIC_TIM1.NVIC_IRQChannelSubPriority=2;
	NVIC_Init(&NVIC_TIM1);
	NVIC_TIM1.NVIC_IRQChannel=TIM5_IRQn;
	NVIC_TIM1.NVIC_IRQChannelPreemptionPriority=1;
	NVIC_TIM1.NVIC_IRQChannelSubPriority=1;
	NVIC_Init(&NVIC_TIM1);
	
	TIM_ITConfig(TIM3,TIM_IT_Update,DISABLE); 
	TIM_ITConfig(TIM4,TIM_IT_Update,DISABLE); 
	TIM_ITConfig(TIM5,TIM_IT_Update,DISABLE); 
	TIM_SetCounter(TIM3,0x00);
	TIM_SetCounter(TIM4,0x00);
	TIM_SetCounter(TIM5,0x00);
	TIM_Cmd(TIM3, ENABLE);
	TIM_Cmd(TIM4, ENABLE);
	TIM_Cmd(TIM5, ENABLE);
}
/*
void TIM3_IRQHandler(void)
{
	int test_flag=0;
	
	if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET) 
	{
	if(test_flag==0)
	{
		
	}
	}
	TIM_ClearITPendingBit(TIM3,TIM_IT_Update);  
}

*/